package com.yanqu.road.web.controller.usercenter.newadmin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.dao.impl.servercenter.CrossServerInfoDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.entity.servercenter.CrossServerInfo;
import com.yanqu.road.entity.servercenter.ProcessInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupRule;
import com.yanqu.road.entity.web.ICrossWebService;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.utils.CrossServerType;
import com.yanqu.road.utils.config.Config;
import com.yanqu.road.utils.string.StringUtils;
import com.yanqu.road.web.WebServer;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 41.跨服商会活动分组隔离
 */
@RestController
@RequestMapping("/usercenter/admin")
public class CenterCrossUnionActivityIsolateController {

    /**
     * 41.1 新增
     */
    @ResponseBody
    @RequestMapping(value = "addUnionActivityIsolate", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String addIsolate(HttpServletRequest request, @RequestBody JSONObject paramObject){

        if(!paramObject.containsKey("type")){
            return AdminResult.failMsg("参数不足").toJsonString();
        }

        UnionActivityGroupRule rule = new UnionActivityGroupRule();
        rule.setActivityType(paramObject.getIntValue("type"));
        rule.setChildType(paramObject.getIntValue("childType"));
        rule.setUnionUid1(paramObject.getString("chamberOfCommerceId"));
        rule.setUnionUid2(paramObject.getString("groupIsolateId"));
        String remark = paramObject.getString("remark");
        if(!StringUtils.isNullOrEmpty(rule.getRemark())){
            rule.setRemark(remark);
        }else {
            rule.setRemark("");
        }
        ArrayList<UnionActivityGroupRule> list = new ArrayList<>();
        list.add(rule);

        boolean success = new AdminCommonDaoImpl().batchInsertUnionActivityGroupRule(list);
        if(!success){
            AdminResult.failMsg("导入失败");
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 41.2 导入
     */
    @ResponseBody
    @RequestMapping(value = "importUnionActivityIsolateList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String importIsolateList(HttpServletRequest request, @RequestBody JSONObject paramObject){

        JSONArray jsonArray = paramObject.getJSONArray("importList");
        if(jsonArray != null && jsonArray.size() > 0) {
            List<UnionActivityGroupRule> list = new ArrayList<>();

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                UnionActivityGroupRule rule = new UnionActivityGroupRule();
                rule.setActivityType(jsonObject.getIntValue("type"));
                rule.setChildType(jsonObject.getIntValue("childType"));
                rule.setUnionUid1(jsonObject.getString("chamberOfCommerceId"));
                rule.setUnionUid2(jsonObject.getString("groupIsolateId"));
                String remark = jsonObject.getString("remark");
                if(!StringUtils.isNullOrEmpty(rule.getRemark())){
                    rule.setRemark(remark);
                }else {
                    rule.setRemark("");
                }
                list.add(rule);
            }

            boolean success = new AdminCommonDaoImpl().batchInsertUnionActivityGroupRule(list);
            if(!success){
                return AdminResult.failMsg("导入失败").toJsonString();
            }
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 41.3 删除
     */
    @ResponseBody
    @RequestMapping(value = "delUnionActivityIsolate", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String delIsolate(HttpServletRequest request, @RequestBody JSONObject paramObject){


//        JSONArray jsonArray = paramObject.getJSONArray("chamberOfCommerceIds");
//        if(jsonArray != null && jsonArray.size() > 0){
//            List<String> unionList = new ArrayList<>();
//            for (int i = 0; i < jsonArray.size(); i++) {
//                unionList.add(jsonArray.getString(i));
//            }
//            boolean success = new AdminCommonDaoImpl().batchDeleteUnionActivityGroupRule(unionList);
//            if(!success){
//                return AdminResult.failMsg("更新失败").toJsonString();
//            }
//        }

        List<Integer> idsList = new ArrayList<>();
        JSONArray jsonArray = paramObject.getJSONArray("ids");
        if(jsonArray != null && jsonArray.size() > 0) {
            for (int i = 0; i < jsonArray.size(); i++) {
                idsList.add(jsonArray.getIntValue(i));
            }
        }
        boolean success = new AdminCommonDaoImpl().deleteUnionActivityGroupRuleById(idsList);
        if(!success){
            return AdminResult.failMsg("更新失败").toJsonString();
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 41.4 查询
     */
    @ResponseBody
    @RequestMapping(value = "searchUnionActivityIsolate", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String searchIsolate(HttpServletRequest request, @RequestBody JSONObject paramObject){

        int channelId = paramObject.getIntValue("channelId");

        List<UnionActivityGroupRule> ruleList = new AdminCommonDaoImpl().getUnionActivityGroupRuleList();

        AdminResult result = AdminResult.defaultInstance();

        int total = ruleList.size();
        JSONArray row = new JSONArray();
        for (UnionActivityGroupRule rule : ruleList) {
            JSONObject object = new JSONObject();
            object.put("id", rule.getId());
            object.put("type", rule.getActivityType());
            object.put("childType", rule.getChildType());
            object.put("chamberOfCommerceId", rule.getUnionUid1());
            object.put("groupIsolateId", rule.getUnionUid2());
            object.put("remark", rule.getRemark());
            row.add(object);
        }
        result.getData().put("total", total);
        result.getData().put("row", row);
        return result.toJsonString();
    }

    /**
     *  41.5 刷新
     */
    @ResponseBody
    @RequestMapping(value = "reloadUnionActivityIsolate", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String reloadCrossServerGroup(HttpServletRequest request, @RequestBody JSONObject jsonObject) {
        int channelId = jsonObject.getIntValue("channelId");

        List<ProcessInfo> processInfoList = new ArrayList<>();

        List<CrossServerInfo> serverInfoList = new CrossServerInfoDaoImpl().getAllChannelCrossServerInfo(channelId);
        serverInfoList.removeIf(next -> (next.getCrossServerType() != CrossServerType.RANK_CROSS_2));

        for (CrossServerInfo crossServerInfo : serverInfoList) {
            if(Config.isDebug() && crossServerInfo.getCrossServerId() != 99900077 && crossServerInfo.getCrossServerId() != 99905020 && crossServerInfo.getCrossServerId() != 99905001){
                continue;
            }

            for (ProcessInfo processInfo : crossServerInfo.getProcessInfoList()) {
                if(processInfo.getServerName().equals("cross_server")) {
                    processInfoList.add(processInfo);
                }
            }
        }

        ExecutorService webExecutor = WebServer.getWebExecutor();
        List<Long> errorCrossServerIdList = new ArrayList<>();
        try {
            //遍历异步通知活动跨服
            CountDownLatch countDownLatch = new CountDownLatch(processInfoList.size());
            JSONObject param = new JSONObject();
            param.put("content", "UnionActivityGroupLockMgr");
            for (ProcessInfo processInfo : processInfoList) {
                webExecutor.execute(() -> {
                    try {
                        String url = "http://" + processInfo.getAddress() + ":" + processInfo.getAdminPort() + "/crossws?wsdl";
                        QName qName = new QName("http://webservice.server.road.yanqu.com/", "GrossWebServiceService");
                        Service service = Service.create(new URL(url), qName);
                        ICrossWebService crossWebService = service.getPort(ICrossWebService.class);
                        String resp = crossWebService.executeAdminOperate("AgentReload|reloadMgr", param.toJSONString(), "Yanqu123");
                        JSONObject result = JSONObject.parseObject(resp);
                        int status = result.getInteger("status");
                        if (status != 1) {
                            errorCrossServerIdList.add((long) processInfo.getServerId());
                        }
                    } catch (Exception e) {
                        errorCrossServerIdList.add((long) processInfo.getServerId());
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }
            //等待
            if (!countDownLatch.await(30, TimeUnit.SECONDS)) {
                ServerListMgr.getLogger().error("刷新超时");
            }
        } catch (Exception e) {
            ServerListMgr.getLogger().error("", e);
        }

        AdminResult result = AdminResult.defaultInstance();
        result.getData().put("serverIds", StringUtils.listToString(errorCrossServerIdList, ","));
        return result.toJsonString();
    }
}
